<template>
  <div style="width: 100%" class="commonTreeSelect">
    <el-select
      v-model="nValue"
      multiple
      clearable
      collapse-tags
      popper-class="tree-select-popper"
      @change="handleSelectChange"
      @remove-tag="handleSelectRmove"
    >
      <el-option :value="selectedValue">
        <!--         <div @click.stop class="device-tree-check-all" v-if="treeData.length">-->
        <!--           <el-checkbox  :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"-->
        <!--                        >全选</el-checkbox>-->
        <!--           <span>-->
        <!--                      <i class="el-icon-arrow-down" style="margin-right: 10px;color: #000000;"-->
        <!--                         :style="isTreeFold?'opacity:0.25':'opacity:0.45'" @click="treeUnfold"></i>-->
        <!--                      <i class="el-icon-arrow-up" style="color: #000000;"-->
        <!--                         :style="isTreeFold?'opacity:0.45':'opacity:0.25'" @click="treeFold"></i>-->
        <!--                    </span>-->
        <!--         </div>-->
        <div
          v-if="isShowAllBtn"
          @click.stop
          class="filter-input-wraapper"
          style="padding: 0 15px"
        >
          <el-input
            size="mini"
            suffix-icon="el-icon-search"
            v-model="filterText"
            placeholder="请输入"
          ></el-input>
        </div>
        <div
          class="tree-wrapper"
          @click.stop
          :style="isShowAllBtn ? 'height: calc(100% - 75px)' : 'height: 100%'"
        >
          <el-tree
            :data="treeData"
            node-key="id"
            ref="tree"
            v-bind="$attrs"
            v-on="$listeners"
            @click.stop.native
            @check-change="handleCheckChange($event)"
            @check="getViewTreeData"
            :filter-node-method="filterNode"
            style="padding: 0 15px"
          >
            <span
              class="custom-tree-node"
              slot-scope="{ node, data }"
              :title="node.label"
              style="
                width: 100%;
                display: flex;
                flex-direction: row;
                justify-content: space-between;
                padding: 0 5px;
              "
            >
              <span>
                <svg-icon v-if="data.userId" icon-class="usericon"></svg-icon>
                <span>{{ node.label }}</span>
                <el-tooltip
                  popper-class="popper-tooltip"
                  v-if="data.purviewFlag === '1'"
                  effect="dark"
                  content="该用户拥有告警的处理权限和查看权限"
                  placement="top"
                >
                  <svg-icon
                    icon-class="readAndhandle"
                    style="opacity: 0.65"
                  ></svg-icon>
                </el-tooltip>
              </span>
              <span v-if="data.root === 1">
                <i
                  class="el-icon-arrow-down"
                  style="margin-right: 10px; color: #000000"
                  :style="isTreeFold ? 'opacity:0.25' : 'opacity:0.45'"
                  @click="treeFold"
                ></i>
                <i
                  class="el-icon-arrow-up"
                  style="color: #000000"
                  :style="isTreeFold ? 'opacity:0.45' : 'opacity:0.25'"
                  @click="treeUnfold"
                ></i>
              </span>
            </span>
          </el-tree>
        </div>
      </el-option>
      <div v-if="isShowAllBtn" class="down-btn" @click="showAllInfo">
        {{ isShowAllInfo ? "取消显示全部处理人" : "显示全部处理人" }}
      </div>
    </el-select>
  </div>
</template>
<script>
export default {
  name: "tree-select-popper",
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    config: {
      // label, value
      type: Object,
      default: () => ({}),
    },
    lastProcess: {
      type: String,
      default: "",
    },
    isShowAllBtn: {
      type: Boolean,
      default: false,
    },
    isShowAllInfo: {
      type: Boolean,
      default: false,
    },
    nextLinkInfo: {
      type: Object,
      default: () => {},
    },
    allUserTreeData: {
      type: Array,
      default: () => [],
    },
    userTreeData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      selectedValue: [],
      nValue: [],
      nId: [],
      isIndeterminate: false,
      checkAll: true,
      isTreeFold: true,
      allNodes: [],
      filterText: "",
      flag: true,
      treeData: [],
    };
  },
  watch: {
    selectedValue(val) {
      this.$emit("change", val);
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    allUserTreeData: {
      handler(val) {
        this.treeData = val;
        if (this.nextLinkInfo?.dataFilterPermiss == 1) {
          this.treeData = this.userTreeData;
        }
        if (this.nextLinkInfo?.customAdmin == 0) {
          this.treeData = this.transferAdminData(this.treeData);
        }
        if (this.lastProcess) {
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys([this.lastProcess]);
            this.handleCheckChange();
            this.getViewTreeData();
          });
        } else {
          this.$nextTick(() => {
            this.checkAllNodes(this.treeData);
          });
        }
      },
      deep: true,
    },
  },
  methods: {
    handleCheckChange(e) {
      const nodes = this.$refs.tree.getCheckedNodes();
      this.selectedValue = nodes.filter((item) => item[this.config.value]);
      this.nValue = this.selectedValue.map((ele) => ele[this.config.label]);
      this.nId = this.selectedValue.map((ele) => ele[this.config.value]);
      this.getViewTreeData();
    },
    handleSelectChange(val) {
      if (val.length === 0) {
        this.$refs.tree.setCheckedKeys([]);
        this.nId = [];
        this.nValue = [];
        this.selectedValue = [];
      }
    },
    handleSelectRmove() {
      this.nId.shift();
      this.selectedValue.shift();
      this.$refs.tree.setCheckedKeys(this.nId);
    },
    handleCheckAllChange(e) {
      this.isIndeterminate = false;
      if (e) {
        this.checkAllNodes();
        this.checkAll = true;
      } else {
        this.$refs.tree.setCheckedKeys([]);
      }
    },
    // 展开
    treeUnfold() {
      this.isTreeFold = false;
      let nodesMap = this.$refs.tree.store.nodesMap;
      for (let key in nodesMap) {
        nodesMap[key].expanded = true;
        nodesMap[key].isCurrent = true;
      }
    },
    // 折叠
    treeFold() {
      this.isTreeFold = true;
      let nodesMap = this.$refs.tree.store.nodesMap;
      for (let key in nodesMap) {
        nodesMap[key].expanded = false;
        nodesMap[key].isCurrent = false;
      }
    },
    getViewTreeData() {
      let allNodes = this.$refs.tree.store._getAllNodes();
      let leafNodes = allNodes.filter((item) => item.isLeaf);
      let leafNodesCode = leafNodes.map((item) => item.data.deviceCode);
      let checkedTreeNode = this.$refs.tree.getCheckedKeys(true);
      this.checkAll = checkedTreeNode.length === leafNodesCode.length;
      this.isIndeterminate =
        0 < checkedTreeNode.length &&
        checkedTreeNode.length < leafNodesCode.length;
      this.isIndeterminate =
        checkedTreeNode.length == 0 ? false : this.isIndeterminate;
    },
    deepGetNodes(arr, data) {
      if (!data) {
        data = this.treeData;
      }
      data.map((item) => {
        arr.push(item.id);
        if (item.children) {
          this.deepGetNodes(arr, item.children);
        }
      });
    },
    checkAllNodes(val) {
      this.deepGetNodes(this.allNodes, val);
      this.$refs.tree.setCheckedKeys(this.allNodes);
      this.handleCheckChange();
    },
    filterNode(value, data) {
      if (!value) {
        return true;
      }
      return data.label.indexOf(value) !== -1;
    },
    // 切换树数据前对当前选中数据重新设置，防止从多数据变为少数据时，checked不匹配
    showAllInfo() {
      if (!this.isShowAllInfo) {
        this.treeData = this.allUserTreeData;
      } else {
        this.treeData = this.allUserTreeData;
        if (this.nextLinkInfo.dataFilterPermiss == 1) {
          this.treeData = this.userTreeData;
        }
        if (this.nextLinkInfo.customAdmin == 0) {
          this.treeData = this.transferAdminData(this.treeData);
        }
      }
      let keys = this.selectedValue.map((item) => item.id);
      this.$refs.tree.setCheckedKeys(keys);
      this.$nextTick(() => {
        this.handleCheckChange();
        // this.getViewTreeData();
      });
      this.$emit("update:isShowAllInfo", !this.isShowAllInfo);
    },
    deepGetAdmin(list, arr) {
      list.map((item) => {
        if (Array.isArray(item.children) && item.children.length > 0) {
          this.deepGetAdmin(item.children, arr);
        } else {
          if (item.tenantAdmin === "1") {
            arr.push(item);
          }
        }
      });
    },
    /**
     * 获取当前树数据的选中状态
     */
    checkTreeChange() {
      // 获取客户管理员列表
      if (!this.isShowAllInfo) {
        let tenantAdminList = [];
        this.deepGetAdmin(this.treeData, tenantAdminList);
        // tenantAdminList.map(item=>{
        //   this.$refs.tree.remove(item)
        // })
        for (const item of tenantAdminList) {
          this.$refs.tree.remove(item);
        }
      }

      this.$nextTick(() => {
        if (this.lastProcess) {
          // lastProcess 回显
          this.$refs.tree.setCheckedKeys([this.lastProcess]);
          this.handleCheckChange();
          this.getViewTreeData();
        } else {
          this.checkAllNodes(this.treeData);
        }
      });
    },
    transferAdminData(list) {
      return list
        .filter((node) => node.tenantAdmin != 1)
        .map((node) => {
          if (node.children) {
            return {
              ...node,
              children: this.transferAdminData(node.children),
            };
          }
          return node;
        });
    },
  },
};
</script>
<style lang="scss">
.tree-select-popper {
  .el-select-dropdown__list {
    .el-select-dropdown__item {
      height: 254px;
      overflow-y: scroll;
      background: #fff;
      padding: 0px;
    }
  }
  .el-scrollbar__thumb {
    display: none;
  }
  .el-select-dropdown__item::after {
    display: none;
  }
  .el-tree {
    height: 100%;
  }
}
</style>
<style>
.tree-select-popper {
  margin-top: 1px !important;
  overflow: hidden;
  z-index: 4000 !important;
}
.tree-select-popper .el-checkbox__label {
  color: #606266 !important;
}
.tree-select-popper .filter-input-wraapper .el-input__validateIcon {
  display: none;
}
.popper-tooltip {
  z-index: 9999 !important;
}
</style>
<style lang="scss" scoped>
.tree-wrapper {
  overflow-y: auto;
}
.down-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 40px;
  width: 100%;
  border-top: 1px solid #eee;
  text-align: center;
  line-height: 40px;
  cursor: pointer;
  color: #ff8889;
  user-select: none;
}
.device-tree-check-all {
  height: 30px;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 0 10px 0 6px;
  line-height: 30px;
}
</style>
